package org.wcms.surrounded.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.wcms.surrounded.Constants;
import org.wcms.surrounded.model.User;
import org.wcms.surrounded.persistence.UserService;
import org.wcms.surrounded.utils.Utils;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class SurrounderUserFilter implements Filter {

    private final UserService userService;
    
    @Inject
    public SurrounderUserFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    	
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;

        User user;
        if (!Utils.hasCookie(httpRequest.getCookies())) {
            user = userService.getUserById(Constants.SURROUNDED_NEW_USER_ID);
        } else {
            Cookie userCookie = Utils.getCookie(httpRequest.getCookies());
            long id = Utils.getIdFromGuid(userCookie.getValue());
            user = userService.getUserById(id);
            
            if (user == null) {
            	//Should never happen, as the concept of "overtaking a username" does no longer exist, but just to be on the safe side...
            	user = userService.getUserById(Constants.SURROUNDED_NEW_USER_ID);            	
            }            
        }        
        
        //refreshing the cookie at the client
        Utils.updateUserSessionAndCookie(httpRequest, httpResponse, user);
        
        chain.doFilter(request, response);
    }
    
    @Override public void destroy() { }
    
    @Override public void init(FilterConfig config) throws ServletException { }

}
